#include "common.h"

#import "NVAAppDelegate.h"

@implementation NVAAppDelegate

- (BOOL) application: (UIApplication*)application didFinishLaunchingWithOptions: (NSDictionary*)launchOptions
{
	NSString *filename;
    
    if(![self CheckFirstRun])
    {
        [self CopyResource:@"QuickStartGuide"];
    }
    
	queue = dispatch_queue_create("com.nva.nvareader", NULL);
    
	// use at most 128M for resource cache
	ctx = fz_new_context(NULL, NULL, 128<<20);
	fz_register_document_handlers(ctx);
    
    //config dropbox
    // Setup Dropbox Here with YOUR OWN APP info
    // #error Dropbox App Key and Secret are required for basic functionality. Add them below AND in the Info.plist file in the URL-Schemes section. Replace the "APP_KEY" text with your app key (make sure to leave the "db-" there)
    DBSession *dbSession = [[DBSession alloc] initWithAppKey:@"30bqvp1xvtpaie3" appSecret:@"k9m0dhl61xv2uge" root:kDBRootDropbox];
    [DBSession setSharedSession:dbSession];
    
	screenScale = [[UIScreen mainScreen] scale];
    
	library = [[NVALibraryController alloc] initWithStyle: UITableViewStylePlain];
    
	navigator = [[UINavigationController alloc] initWithRootViewController: library];
	[[navigator navigationBar] setTranslucent: YES];
	[[navigator toolbar] setTranslucent: YES];
	[navigator setDelegate: self];
    
	window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
	[window setBackgroundColor: [UIColor grayColor]];
	[window setRootViewController: navigator];
	[window makeKeyAndVisible];
    
	filename = [[NSUserDefaults standardUserDefaults] objectForKey: @"OpenDocumentKey"];
	if (filename)
		[library openDocument: filename];
    
	filename = [launchOptions objectForKey: UIApplicationLaunchOptionsURLKey];
	NSLog(@"urlkey = %@\n", filename);
    
    [self SetNavAppearance];
    
	return YES;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
	NSLog(@"openURL: %@\n", url);
	if ([url isFileURL]) {
		NSString *path = [url path];
		NSString *dir = [NSString stringWithFormat: @"%@/Documents/", NSHomeDirectory()];
		path = [path stringByReplacingOccurrencesOfString:@"/private" withString:@""];
		path = [path stringByReplacingOccurrencesOfString:dir withString:@""];
		NSLog(@"file relative path: %@\n", path);
		[library openDocument:path];
		return YES;
	}
    if ([[DBSession sharedSession] handleOpenURL:url]) {
        if ([[DBSession sharedSession] isLinked]) {
            NSLog(@"App linked successfully!");
            // At this point you can start making API calls
        }
        return YES;
    }
	return NO;
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
	printf("applicationDidEnterBackground!\n");
	[[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
	printf("applicationWillEnterForeground!\n");
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
	printf("applicationDidBecomeActive!\n");
}

- (void)applicationWillTerminate:(UIApplication *)application
{
	printf("applicationWillTerminate!\n");
	[[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
	printf("applicationDidReceiveMemoryWarning\n");
}

- (void) dealloc
{
	dispatch_release(queue);
	[library release];
	[navigator release];
	[window release];
	[super dealloc];
}
-(void) SetNavAppearance
{
    NSString *ver = [[UIDevice currentDevice] systemVersion];
    int ver_int = [ver intValue];
    
    if (ver_int < 7) {
        
    }
    else {
        [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:0.23 green:0.35 blue:0.6 alpha:1]];
        NSDictionary *navbarTitleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                                   [UIColor whiteColor],UITextAttributeTextColor,
                                                   [UIColor whiteColor], UITextAttributeTextShadowColor,
                                                   [NSValue valueWithUIOffset:UIOffsetMake(0, 0)], UITextAttributeTextShadowOffset, nil];
        [[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];
        [[UISlider appearance] setTintColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:1]];
        [[UISlider appearance] setBackgroundColor:[UIColor colorWithRed:0.23 green:0.35 blue:0.6 alpha:1]];
    }
}

-(BOOL) CheckFirstRun
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    if([ud boolForKey:@"haveRunB4"])
    {
        return true;
    }
    else
    {
        [ud setBool:true forKey:@"haveRunB4"];
        [ud synchronize];
        
        return FALSE;
    }
}
#pragma mark - dodd write file

-(void) CopyResource:(NSString *)name
{
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"nva"];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains
    (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *savePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.nva",name]];
    
    NSFileManager *fm = [NSFileManager defaultManager];
    [fm copyItemAtPath:path toPath:savePath error:nil];
}


@end